/**
 * User: alesj
 * Date: 2005.3.25
 * Time: 12:04:48
 * 
 * (C) Genera Lynx d.o.o.
 */

package com.generalynx.ecos.page;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Criteria;
import org.springframework.jdbc.datasource.DataSourceUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author Pietro Polsinelli ppolsinelli@open-lab.com
 * @author Ales Justin ales.justin@gmail.com
 */
public class DoubleQueryPage extends HibernatePage {

    public DoubleQueryPage(DataSource dataSource,
                           String sqlCountQuery,
                           Query query,
                           int pageNumber,
                           int pageSize) {
        super(pageNumber, pageSize);
        try {
            queryTotalElements(dataSource, sqlCountQuery);
            createElements(query);
        } catch (SQLException e) {
            throw new HibernateException(e);
        }
    }

    public DoubleQueryPage(DataSource dataSource,
                           String sqlCountQuery,
                           Criteria criteria,
                           int pageNumber,
                           int pageSize) {
        super(pageNumber, pageSize);
        try {
            queryTotalElements(dataSource, sqlCountQuery);
            createElements(criteria);
        } catch (SQLException e) {
            throw new HibernateException(e);
        }
    }

    private void queryTotalElements(DataSource dataSource, String sqlCountQuery)
            throws SQLException {
        Connection connection = DataSourceUtils.getConnection(dataSource);
        try {
            ResultSet resultSet = connection.prepareStatement(sqlCountQuery).executeQuery();
            resultSet.next();
            totalElements = resultSet.getInt(1) - 1;
        } finally {
            DataSourceUtils.releaseConnection(connection, dataSource);
        }
    }

    public int getTotalNumberOfElements() {
        return totalElements;
    }

}